package cn.laixueit.service.impl;

import cn.laixueit.commons.Utils;
import cn.laixueit.mapper.UserMapper;
import cn.laixueit.pojo.User;
import cn.laixueit.pojo.UserExample;
import cn.laixueit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.selectByExample(null);
    }

    @Override
    public Integer sendMail(String email) {
        Integer code = Utils.sendEmail(email);
        return code;
    }

    @Override
    public Boolean register(User user) {

        String email = user.getEmail();
        //如果邮箱已经存在域数据库
        //return false;
        String password = user.getPassword();

        String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        user.setPassword(md5Pwd);

        userMapper.insertSelective(user);
        return true;
    }

    @Override
    public Boolean login(String username, String password) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        criteria.andUsernameEqualTo(username).andPasswordEqualTo(md5Pwd);
        long count = userMapper.countByExample(example);
        return count==1;
    }

    @Override
    public User getUser(String username) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> userList = userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }
        return userList.get(0);
    }
}
